<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-button
        v-permission="['POST /admin/delivery/notice/create']"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate"
        >创建</el-button
      >
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="正在加载..."
      :header-cell-style="{
        background: 'rgba(239, 241, 244, 0.2)',
        color: '#333333',
      }"
      border
      fit
    >
      <el-table-column
        align="center"
        width="100px"
        label="ID"
        prop="id"
        sortable
      />

      <el-table-column
        align="center"
        min-width="200px"
        label="标题"
        prop="title"
      />

      <el-table-column
        align="center"
        min-width="400px"
        label="内容"
        prop="content"
      />

      <el-table-column
        align="center"
        label="操作"
        width="120"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-permission="['POST /admin/delivery/notice/update']"
            type="text"
            @click="handleUpdate(scope.row)"
            >编辑</el-button
          >
          <el-button
            style="color: red"
            v-permission="['POST /admin/delivery/notice/delete']"
            type="text"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog
      width="50%"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="100px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="dataForm.title" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="dataForm.content"
            :rows="8"
            type="textarea"
            placeholder="请输入配送须知内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          v-if="dialogStatus == 'create'"
          type="primary"
          @click="createData"
          >确定</el-button
        >
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDeliveryNotice, createDeliveryNotice, updateDeliveryNotice, deleteDeliveryNotice } from "@/api/deliveryNotice";
import Pagination from "@/components/Pagination";

export default {
  name: "DeliveryNotice",
  components: { Pagination },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        title: undefined,
        sort: "add_time",
        order: "desc",
      },
      dataForm: {
        id: undefined,
        title: "",
        content: "",
      },
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "创建",
      },
      rules: {
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" },
        ],
        content: [{ required: true, message: "内容不能为空", trigger: "blur" }],
      },
      downloadLoading: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.listLoading = true;
      listDeliveryNotice(this.listQuery)
        .then((response) => {
          this.list = response.data.data.list;
          this.total = response.data.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        title: "",
        content: "",
      };
    },
    handleCreate() {
      this.resetForm();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    createData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          createDeliveryNotice(this.dataForm)
            .then((response) => {
              this.list.unshift(response.data.data);
              this.dialogFormVisible = false;
              this.$message.success({
                title: "成功",
                message: "创建成功",
              });
            })
            .catch((response) => {
              this.$message.error({
                title: "失败",
                message: response.data.errmsg,
              });
            });
        }
      });
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row);
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          updateDeliveryNotice(this.dataForm)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v);
                  this.list.splice(index, 1, this.dataForm);
                  break;
                }
              }
              this.dialogFormVisible = false;
              this.$message.success({
                title: "成功",
                message: "更新成功",
              });
            })
            .catch((response) => {
              this.$message.error({
                title: "失败",
                message: response.data.errmsg,
              });
            });
        }
      });
    },
    handleDelete(row) {
      this.$confirm("数据删除后不可恢复，是否确认删除此条数据？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        deleteDeliveryNotice({ id: row.id })
          .then((response) => {
            this.$message.success({
              title: "成功",
              message: "删除成功",
            });
            this.getList();
          })
          .catch((response) => {
            this.$message.error({
              title: "失败",
              message: response.data.errmsg,
            });
          });
      });
    },
  },
};
</script>
